package com.af.security.auth.util.session;

import com.af.service.AfI18nService;
import com.af.service.AfRedirectService;
import com.af.system.util.AfServletUtils;
import com.af.system.api.result.AfResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

/**
 * @author : zhenyun.su
 * @comment : 同一账号超过最大会话数时，会话失效触发执行
 * @since : 2020/3/30
 */

@Component
public class AfSessionExpiredStrategy implements SessionInformationExpiredStrategy {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private AfRedirectService redirectService;
    private AfI18nService i18nService;

    public AfSessionExpiredStrategy(AfRedirectService redirectService, AfI18nService i18nService) {
        this.redirectService = redirectService;
        this.i18nService = i18nService;
    }

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent sessionInformationExpiredEvent) throws IOException, ServletException {
        HttpServletRequest request = sessionInformationExpiredEvent.getRequest();
        HttpServletResponse response = sessionInformationExpiredEvent.getResponse();
        Locale locale = AfServletUtils.getRequestLocale(request);
        String msg = i18nService.getI18n("alert.security.max-session.invalid", null, locale);
        logger.debug("SessionInformationExpiredStrategy, {}", sessionInformationExpiredEvent.getSessionInformation());
        redirectService.redirectJson(response, AfResultUtils.failure(msg, null));
    }
}
